/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.workflow.user;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.*;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.service.IconType;
import com.je.rbac.service.company.RbacDepartmentService;
import java.util.*;

/**
 * 责任链模式，一个处理者既处理请求，又把请求传递给下一个处理者
 */

public class FilterChain implements Filter {
    MetaService metaService = SpringContextHolder.getBean(MetaService.class);
    BeanService beanService = SpringContextHolder.getBean(BeanService.class);

    RbacDepartmentService rbacDepartmentService = SpringContextHolder.getBean(RbacDepartmentService.class);
    private int index = 0;

    private List<Filter> filters = new ArrayList<Filter>();

    public FilterChain add(Filter filter) {
        filters.add(filter);
        return this;
    }

    @Override
    public void doFilter(ParserUserBo parserUserBo, JSONTreeNode jsonTreeNode, FilterChain filterChain) {
        if (index == filters.size()) {
            jsonTreeNode = JsonTreeContext.getJsonTree("ROOT");
        }

        Filter filter = filters.get(index);
        index++;
        filter.handler(parserUserBo, jsonTreeNode, filterChain);
    }

    @Override
    public void handler(ParserUserBo params, JSONTreeNode jsonTreeNode, FilterChain filterChain) {

    }

    /**
     * 查询唯一信息，账号部门视图 JE_RBAC_VACCOUNTDEPT
     *
     * @param userId
     * @return
     */
    public DynaBean findVacCountDeptUserById(String userId) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        DynaBean accountDept = metaService.selectOne("JE_RBAC_VACCOUNTDEPT",
                ConditionsWrapper.builder().eq("JE_RBAC_ACCOUNTDEPT_ID", userId).eq("SY_STATUS", "1"));
        return accountDept;
    }

    /**
     * 构建公司、部门、用户树
     *
     * @param multiple
     * @param addOwn
     * @param userId
     * @param companyIds
     * @return
     */
    public JSONTreeNode buildCompanyDepartmentUserTreeAddOwn(Boolean multiple, Boolean addOwn, String userId, String... companyIds) {
        //公司部门树
        JSONTreeNode companyNode = buildCompanyTreeData(false, false, companyIds);
        List<DynaBean> departmentUserBeanList;
        ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder();
        if (companyIds == null || companyIds.length <= 0) {
            if (!addOwn) {
                conditionsWrapper = ConditionsWrapper.builder().ne("JE_RBAC_ACCOUNTDEPT_ID", userId);
            }

            departmentUserBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", conditionsWrapper.eq("SY_STATUS", "1").orderByAsc("SY_ORDERINDEX"));
        } else {
            if (!addOwn) {
                conditionsWrapper = ConditionsWrapper.builder().ne("JE_RBAC_ACCOUNTDEPT_ID", userId);
            }
            conditionsWrapper.in("SY_COMPANY_ID", companyIds);
            departmentUserBeanList = metaService.select("JE_RBAC_VACCOUNTDEPT", conditionsWrapper.eq("SY_STATUS", "1").orderByAsc("SY_ORDERINDEX"));
        }

        recursiveDepartmentUserTreeNode(companyNode, departmentUserBeanList, multiple);
        return companyNode;
    }

    public void recursiveDepartmentUserTreeNode(JSONTreeNode rootNode, List<DynaBean> departmentUserBeanList, Boolean multiple) {
        if ("department".equals(rootNode.getNodeInfoType())) {
            for (DynaBean eachDepartmentUserBean : departmentUserBeanList) {
                eachDepartmentUserBean.put("DEPARTMENT_ICON", IconType.TCONTYPE_ROLE.getVal());
                if (!rootNode.getId().equals(eachDepartmentUserBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                    continue;
                }
                parseAccountDepartmentToTree(rootNode, eachDepartmentUserBean, multiple, true);
            }
        }

        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            return;
        }

        for (JSONTreeNode eachChildNode : rootNode.getChildren()) {
            recursiveDepartmentUserTreeNode(eachChildNode, departmentUserBeanList, multiple);
        }
    }

    /**
     * 构建人员信息
     *
     * @param resultJSONTreeNode
     * @param user
     * @param multiple
     * @param disFlag
     */
    public static void parseAccountDepartmentToTree(JSONTreeNode resultJSONTreeNode, DynaBean user, Boolean multiple, Boolean disFlag) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(user.getStr("JE_RBAC_ACCOUNTDEPT_ID"));
        node.setCode(user.getStr("ACCOUNT_CODE"));
        //排除部门，组织架构；其余调用均添加部门标示
        if (disFlag) {
            node.setText(user.getStr("ACCOUNT_NAME") + "(" + user.getStr("ACCOUNTDEPT_DEPT_NAME") + ")");
        } else {
            node.setText(user.getStr("ACCOUNT_NAME"));
        }
        node.setNodeType("LEAF");
        JSONObject nodeInfo = new JSONObject();
        nodeInfo.put("sex", user.getStr("ACCOUNT_SEX"));
        nodeInfo.put("ACCOUNT_NAME", user.getStr("ACCOUNT_NAME"));
        node.setNodeInfo(nodeInfo.toJSONString());
        node.setNodeInfoType("json");
        node.setIcon(IconType.TCONTYPE_ROLE.getVal());
        node.setParent(resultJSONTreeNode.getId());
        node.setChecked(multiple);
        node.setLayer(resultJSONTreeNode.getLayer() + 1);
        node.setBean(user.getValues());
        //节点信息放入上下文
        JsonTreeContext.putJsonTree(node.getId(), node);
        JsonTreeContext.getJsonTree(resultJSONTreeNode.getId()).getChildren().add(node);

    }

    /**
     * 获取公司部门树
     *
     * @return
     */
    public JSONTreeNode buildCompanyTreeData(Boolean colorFlag, Boolean justCompany, String... companyIds) {

        //查询所有公司放入map中
        List<DynaBean> companyList = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder());
        Map<String, String> companyMap = new HashMap<>();
        for (DynaBean eachBean : companyList) {
            companyMap.put(eachBean.getPkValue(), eachBean.getStr("COMPANY_CODE"));
        }

        List<DynaBean> allBeanList;
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        if (companyIds != null && companyIds.length > 0) {
            List<String> companyIdList = Splitter.on(",").splitToList(Joiner.on(",").join(companyIds));
            allBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder()
                    .in("ID", companyIdList).eq("TYPE", "company").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
            for (DynaBean eachBean : allBeanList) {
                if ("company".equals(eachBean.getStr("TYPE"))) {
                    JSONTreeNode node = buildTreeNode(rootNode.getId(), eachBean, colorFlag);
                    //节点信息放入上下文
                    JsonTreeContext.putJsonTree(node.getId(), node);
                    JsonTreeContext.getJsonTree(rootNode.getId()).getChildren().add(node);
                    //查找子级
                    List<DynaBean> childBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().like("SY_PATH", "%" + eachBean.getStr("ID") + "%").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
                    if (justCompany) {
                        childBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("TYPE", "company").like("SY_PATH", "%" + eachBean.getStr("ID") + "%").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
                    }
                    //递归存放子级
                    recursionDynaBeanTree(node, childBeanList, companyMap, colorFlag);
                }
            }
        } else {
            allBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
            for (DynaBean eachBean : allBeanList) {
                if ("ROOT".equals(eachBean.getStr("SY_PARENT")) && "company".equals(eachBean.getStr("TYPE"))) {
                    JSONTreeNode node = buildTreeNode(rootNode.getId(), eachBean, colorFlag);
                    //节点信息放入上下文
                    JsonTreeContext.putJsonTree(node.getId(), node);
                    JsonTreeContext.getJsonTree(rootNode.getId()).getChildren().add(node);
                    //查找子级
                    List<DynaBean> childBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().like("SY_PATH", "%" + eachBean.getStr("ID") + "%").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
                    if (justCompany) {
                        childBeanList = metaService.select("JE_RBAC_VCOMPANYDEPT", ConditionsWrapper.builder().eq("TYPE", "company").like("SY_PATH", "%" + eachBean.getStr("ID") + "%").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
                    }
                    //递归存放子级
                    recursionDynaBeanTree(node, childBeanList, companyMap, colorFlag);
                }
            }
        }
        return JsonTreeContext.getJsonTree(rootNode.getId());
    }

    /**
     * 解析公司部门视图信息为treeNode
     *
     * @param parentNodeId
     * @param bean
     * @param colorFlag    是否设置 颜色
     */
    public JSONTreeNode buildTreeNode(String parentNodeId, DynaBean bean, Boolean colorFlag) {
        JSONTreeNode node = new JSONTreeNode();
        node.setParent(parentNodeId);
        node.setLeaf(true);
        node.setId(bean.getStr("ID"));
        node.setCode(bean.getStr("CODE"));
        node.setText(bean.getStr("NAME"));
        node.setNodeType(bean.getStr("SY_NODETYPE"));
        node.setNodeInfoType(bean.getStr("TYPE"));
        node.setIcon(bean.getStr("ICON"));
        if (colorFlag) {
            if (IconType.TCONTYPE_COMPANY.getVal().equals(bean.getStr("ICON"))) {
                node.setIconColor(IconType.TCONTYPE_COMPANY.getIconColor());
            } else if (IconType.TCONTYPE_GROUP.getVal().equals(bean.getStr("ICON"))) {
                node.setIconColor(IconType.TCONTYPE_GROUP.getIconColor());
            } else if (IconType.TCONTYPE_DEPART.getVal().equals(bean.getStr("ICON"))) {
                node.setIconColor(IconType.TCONTYPE_DEPART.getIconColor());
            }
        }
        node.setLayer(bean.getStr("SY_LAYER"));
        node.setTreeOrderIndex(bean.getStr("SY_TREEORDERINDEX"));
        node.setOrderIndex(bean.getStr("SY_ORDERINDEX"));
        node.setNodePath(bean.getStr("SY_PATH"));
        node.setBean(bean.getValues());
        return node;
    }

    /***
     * 递归修改树形属性
     */
    private void recursionDynaBeanTree(JSONTreeNode parentNode, List<DynaBean> childBeanList, Map<String, String> companyMap, Boolean colorFlag) {
        if (childBeanList == null || childBeanList.isEmpty()) {
            return;
        }
        for (DynaBean eachBean : childBeanList) {
            if (parentNode.getId().equals(eachBean.getStr("SY_PARENT"))) {
                JSONTreeNode node = buildTreeNode(parentNode.getId(), eachBean, colorFlag);
                if (eachBean.getStr("TYPE").equals("department")) {
                    node.getBean().put("COMPANY_CODE", companyMap.get(eachBean.getStr("SY_COMPANY_ID")));
                }
                //子公司节点信息放入上下文
                JsonTreeContext.putJsonTree(node.getId(), node);
                JsonTreeContext.getJsonTree(parentNode.getId()).getChildren().add(node);

                recursionDynaBeanTree(node, childBeanList, companyMap, colorFlag);
//                parentNode.getChildren().add(node);
            }
        }
    }

    /**
     * 构建公司树
     *
     * @param companyId
     * @return
     */
    public JSONTreeNode buildCompanyTree(String companyId) {
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        DynaBean table = beanService.getResourceTable("JE_RBAC_COMPANY");
        List<DynaBean> columns = (List<DynaBean>) table.get(BeanService.KEY_TABLE_COLUMNS);
        JSONTreeNode template = beanService.buildJSONTreeNodeTemplate(columns);

        List<DynaBean> allCompanyBeanList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(companyId)) {
            allCompanyBeanList = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder()
                    .eq("JE_RBAC_COMPANY_ID", companyId).eq("SY_STATUS", "1").apply("ORDER BY SY_TREEORDERINDEX ASC,SY_ORDERINDEX ASC"));
        }

        for (DynaBean eachBean : allCompanyBeanList) {
            if (!Strings.isNullOrEmpty(companyId)) {
//                if("ROOT".equals(eachBean.getStr("SY_PARENT"))){
                JSONTreeNode node = buildCompanyTreeNode(template, rootNode.getId(), eachBean);
                if (node != null) {

                    JsonTreeContext.putJsonTree(node.getId(), node);
                    JsonTreeContext.getJsonTree(rootNode.getId()).getChildren().add(node);
                    rootNode.getChildren().add(node);
                }
//                }
            }
        }

        //递归形成树形结构
        for (JSONTreeNode eachNode : rootNode.getChildren()) {
            recursiveJsonTreeNode(template, eachNode, allCompanyBeanList);
        }

        return rootNode;
    }

    private void recursiveJsonTreeNode(JSONTreeNode template, JSONTreeNode rootNode, List<DynaBean> list) {
        if (list == null || list.isEmpty()) {
            return;
        }

        JSONTreeNode treeNode;
        for (DynaBean eachBean : list) {
            if (!Strings.isNullOrEmpty(rootNode.getId()) && !Strings.isNullOrEmpty(eachBean.getStr("SY_PARENT"))) {
                if (rootNode.getId().equals(eachBean.getStr("SY_PARENT"))) {
                    treeNode = buildCompanyTreeNode(template, rootNode.getId(), eachBean);
                    rootNode.getChildren().add(treeNode);

                    JsonTreeContext.putJsonTree(treeNode.getId(), treeNode);
                    JsonTreeContext.getJsonTree(rootNode.getId()).getChildren().add(treeNode);
                }
            }
        }

        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            rootNode.setLeaf(true);
            return;
        }

        rootNode.setLeaf(false);

        for (JSONTreeNode eachNode : rootNode.getChildren()) {
            recursiveJsonTreeNode(template, eachNode, list);
        }

    }

    /**
     * 构建树形节点
     *
     * @param template     模板
     * @param parentNodeId 父节点ID
     * @param bean         当前bean
     * @return
     */
    public JSONTreeNode buildCompanyTreeNode(JSONTreeNode template, String parentNodeId, DynaBean bean) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(bean.getPkValue());
        node.setParent(parentNodeId);
        node.setLeaf(true);
        if (StringUtil.isNotEmpty(template.getText())) {
            node.setText(bean.getStr(template.getText()));
        }
        if (StringUtil.isNotEmpty(template.getCode())) {
            node.setCode(bean.getStr(template.getCode()));
        }
        //节点信息
        node.setNodeInfo(bean.getStr("COMPANY_CODE"));
        //节点信息类型
        node.setNodeInfoType("company");
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //节点路径
        if (StringUtil.isNotEmpty(template.getNodePath())) {
            node.setNodePath(bean.getStr(template.getNodePath()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        }
        //树形排序
        if (StringUtil.isNotEmpty(template.getTreeOrderIndex())) {
            node.setTreeOrderIndex(bean.getStr(template.getTreeOrderIndex()));
        }
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //图标样式
        if (StringUtil.isNotEmpty(template.getIcon())) {
            node.setIcon(bean.getStr(template.getIcon()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        } else {
            node.setDisabled("0");
        }
        //描述
        if (StringUtil.isNotEmpty(template.getDescription())) {
            node.setDescription(bean.getStr(template.getDescription()));
        }
        //排序
        if (StringUtil.isNotEmpty(template.getOrderIndex())) {
            node.setOrderIndex(bean.getStr(template.getOrderIndex()) + "");
        }
        node.setBean(bean.getValues());
        return node;
    }

    /***
     * 构建部门树结构
     * @param template  数据模板
     * @param rootNote  树形根节点
     * @param list      部门数据
     * @param countDepts    部门人员数据
     * @param multiple
     */
    public void recursiveSpecialDeptJsonTreeNode(JSONTreeNode template, JSONTreeNode rootNote, List<DynaBean> list, List<DynaBean> countDepts, Boolean multiple) {
        if (list == null || list.isEmpty()) {
            return;
        }
        //构建当前部门账号
        if (countDepts != null && countDepts.size() > 0) {
            for (DynaBean eachAccoutDeptBean : countDepts) {
                if (rootNote.getBean().get("JE_RBAC_DEPARTMENT_ID").equals(eachAccoutDeptBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                    //构建当前部门下人员信息
                    parseAccountDepartmentToTree(rootNote, eachAccoutDeptBean, multiple, true);
                }
            }
        }

        //构建子级部门、账号
        for (DynaBean eachBean : list) {
            if (rootNote.getId().equals(eachBean.getStr("SY_PARENT"))) {
                JSONTreeNode departmentNode = buildDeptTreeNode(template, rootNote.getId(), eachBean);
                JsonTreeContext.putJsonTree(departmentNode.getId(), departmentNode);
                JsonTreeContext.getJsonTree(rootNote.getId()).getChildren().add(departmentNode);
                //构建树形结构-加入账号node数据
                recursiveDeptAccountTreeNode(departmentNode, countDepts, multiple);
                recursiveDepartmentJsonTreeNode(template, departmentNode, list, countDepts, multiple);


            }
        }
    }

    /***
     * 构建部门账号
     * @param rootNode  部门节点
     * @param countDepts    部门人员
     */
    public void recursiveDeptAccountTreeNode(JSONTreeNode rootNode, List<DynaBean> countDepts, Boolean multiple) {
        if ("department".equals(rootNode.getNodeInfoType())) {
            for (DynaBean countDeptBean : countDepts) {
                if (rootNode.getBean().get("JE_RBAC_DEPARTMENT_ID") == null || !rootNode.getBean().get("JE_RBAC_DEPARTMENT_ID").equals(countDeptBean.getStr("ACCOUNTDEPT_DEPT_ID"))) {
                    continue;
                }
                parseAccountDepartmentToTree(rootNode, countDeptBean, multiple, true);
            }
        }
        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            return;
        }
        for (JSONTreeNode eachChildNode : rootNode.getChildren()) {
            recursiveDeptAccountTreeNode(eachChildNode, countDepts, multiple);
        }
    }

    /***
     * 递归构建部门树节点
     * @param template
     * @param rootNode
     * @param list
     * @param countDepts
     * @param multiple
     */
    public void recursiveDepartmentJsonTreeNode(JSONTreeNode template, JSONTreeNode rootNode, List<DynaBean> list, List<DynaBean> countDepts, Boolean multiple) {
        if (list == null || list.isEmpty()) {
            return;
        }
        JSONTreeNode treeNode;
        for (DynaBean eachBean : list) {
            if (null != rootNode.getBean().get("JE_RBAC_DEPARTMENT_ID") && rootNode.getBean().get("JE_RBAC_DEPARTMENT_ID").equals(eachBean.getStr("SY_PARENT"))) {
                treeNode = buildDeptTreeNode(template, rootNode.getId(), eachBean);
                JsonTreeContext.putJsonTree(treeNode.getId(), treeNode);
                JsonTreeContext.getJsonTree(rootNode.getId()).getChildren().add(treeNode);
                //构建树形结构-加入账号node数据
                recursiveDeptAccountTreeNode(treeNode, countDepts, multiple);

            }
        }

        if (rootNode.getChildren() == null || rootNode.getChildren().isEmpty()) {
            rootNode.setLeaf(true);
            return;
        }
        rootNode.setLeaf(false);

        for (JSONTreeNode eachNode : rootNode.getChildren()) {
            recursiveDepartmentJsonTreeNode(template, eachNode, list, countDepts, multiple);
        }
    }

    /**
     * 构建树形节点
     *
     * @param template     模板
     * @param parentNodeId 父节点ID
     * @param bean         当前bean
     * @return
     */
    public JSONTreeNode buildDeptTreeNode(JSONTreeNode template, String parentNodeId, DynaBean bean) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(bean.getPkValue());
        node.setParent(parentNodeId);
        node.setLeaf(true);
        if (StringUtil.isNotEmpty(template.getText())) {
            node.setText(bean.getStr(template.getText()));
        }
        if (StringUtil.isNotEmpty(template.getCode())) {
            node.setCode(bean.getStr(template.getCode()));
        }
        //节点信息
        node.setNodeInfo(bean.getStr(template.getCode()));
        //节点信息类型
        node.setNodeInfoType("department");
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //节点路径
        if (StringUtil.isNotEmpty(template.getNodePath())) {
            node.setNodePath(bean.getStr(template.getNodePath()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        }
        //树形排序
        if (StringUtil.isNotEmpty(template.getTreeOrderIndex())) {
            node.setTreeOrderIndex(bean.getStr(template.getTreeOrderIndex()));
        }
        //节点类型
        if (StringUtil.isNotEmpty(template.getNodeType())) {
            node.setNodeType(bean.getStr(template.getNodeType()));
        }
        //图标样式
        if (StringUtil.isNotEmpty(template.getIcon())) {
            node.setIcon(bean.getStr(template.getIcon()));
        }
        //是否禁用
        if (StringUtil.isNotEmpty(template.getDisabled())) {
            node.setDisabled(bean.getStr(template.getDisabled()));
        } else {
            node.setDisabled("0");
        }
        //描述
        if (StringUtil.isNotEmpty(template.getDescription())) {
            node.setDescription(bean.getStr(template.getDescription()));
        }
        //排序
        if (StringUtil.isNotEmpty(template.getOrderIndex())) {
            node.setOrderIndex(bean.getStr(template.getOrderIndex()) + "");
        }
        node.setBean(bean.getValues());
        return node;
    }

    public void buildDeptUserTree(Map<String, List<DynaBean>> deptListMap, Boolean multiple, String departmentId, JSONTreeNode companyNode) {
        //构建部门树
        DynaBean table = beanService.getResourceTable("JE_RBAC_DEPARTMENT");
        List<DynaBean> columns = (List<DynaBean>) table.get(BeanService.KEY_TABLE_COLUMNS);
        JSONTreeNode template = beanService.buildJSONTreeNodeTemplate(columns);
        DynaBean deptParentBean = metaService.selectOne("JE_RBAC_DEPARTMENT",
                ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", departmentId));
        deptParentBean.put("DEPARTMENT_ICON", IconType.TCONTYPE_DEPART.getVal());
        JSONTreeNode parentNode = buildDeptTreeNode(template, companyNode.getId(), deptParentBean);
        //节点信息类型
        parentNode.setNodeInfo("department");
        parentNode.setNodeInfoType("department");

        JsonTreeContext.putJsonTree(parentNode.getId(), parentNode);
        JsonTreeContext.getJsonTree(companyNode.getId()).getChildren().add(parentNode);
        //构建用户信息
        recursiveDepartmentUserTreeNode(JsonTreeContext.getJsonTree("ROOT"), deptListMap.get(departmentId), multiple);
    }

    /**
     * 查找部门所属公司，在不在树上，并构建公司部门人员信息
     */
    public void checkCompany(Map<String, List<DynaBean>> deptListMap, Boolean multiple) {
        Set<String> departmentIds = deptListMap.keySet();
        for (String departmentId : departmentIds) {
            DynaBean deptBean = metaService.selectOne("JE_RBAC_VCOMPANYDEPT",
                    ConditionsWrapper.builder().eq("ID", departmentId));
            if (deptBean == null) {
                continue;
            }
            String companyId = deptBean.getStr("SY_COMPANY_ID");
            if (Strings.isNullOrEmpty(companyId)) {
                continue;
            }
            if (JsonTreeContext.getJsonTree(departmentId) == null) {
                //部门不在树上，部门所属公司也不在树上，构建部门公司树
                //部门不在树上，部门所属公司在树上,在公司下add部门人员树
                if (JsonTreeContext.getJsonTree(companyId) == null) {
                    //构建公司树
                    JSONTreeNode companyRootNode = buildCompanyTree(companyId);
                    for (JSONTreeNode companyNode : companyRootNode.getChildren()) {
                        buildDeptUserTree(deptListMap, multiple, departmentId, companyNode);
                    }

                } else {
                    JSONTreeNode companyNode = JsonTreeContext.getJsonTree(companyId);
                    buildDeptUserTree(deptListMap, multiple, departmentId, companyNode);

                }
            } else {
                //部门在树上的话，直接add人员信息
                JSONTreeNode parentTreeNode = JsonTreeContext.getJsonTree(departmentId);
                //构建用户信息
                recursiveDepartmentUserTreeNode(parentTreeNode, deptListMap.get(departmentId), multiple);
            }
        }

    }
}